package connection;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Scanner;

import Framework.Main;

public class Connection {

	Socket socket;
	private PrintWriter out;
	Scanner in;
	String player;
	HashMap<Integer, String> board;
	Reader r;
	public String[] playerList = new String[] {};
	public String[] gameList = new String[] {};
	Main main;

	public Connection(String name, String IP, int port, Main main) {
		try {
			main.lock.lock();
			try {
				this.main = main;
				player = name;
				socket = new Socket(IP, port);
				out = new PrintWriter(socket.getOutputStream(), true);
				in = new Scanner(new InputStreamReader(socket.getInputStream()));
				board = new HashMap<Integer, String>();
			} finally {
				main.lock.unlock();
			}
			r = new Reader(IP, port, this);
			new Thread(r).start();
			login();
			getGameList();
			getPlayerList();
		} catch (UnknownHostException e) {
			System.out.println(e);
		} catch (IOException e) {
			System.out.println(e);
		}
	}

	public void write(String string) {
		out.println(string);
	}

	private void login() {
		write("login " + player);
	}

	public boolean isAlive() {
		return socket.isConnected();
	}

	public void forfeit() {
		write("forfeit");
	}

	public void move(int move) {
		write("move " + move);
	}

	public void challenge(String player, String game) {
		write("challenge \"" + player + "\" \"" + game + "\"");
	}

	public void subscribe(String game) {
		write("subscribe " + game);
	}

	public void exit() {
		write("logout");
	}

	public void getGameList() {
		write("get gamelist");
	}

	public void getPlayerList() {
		write("get playerlist");
	}

	public void accept(String nr) {
		write("challenge accept " + nr);
	}
}